package jsyf.oa.service.wechat.service_company;

import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.BaseUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.wechat.service_otherCompany.CompanyMessageDao;

import jsyf.oa.facade.wechat.config.WeChatConst;
import jsyf.oa.facade.wechat.service_company.CompanyTokenFacade;
import jsyf.oa.facade.wechat.service_company.WechatSynchronizationFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jjx on 2018/3/27.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class WechatSynchronizationService implements WechatSynchronizationFacade {

    @Autowired
    private CompanyTokenFacade companyTokenFacade;

    @Autowired
    private CompanyMessageDao companyMessageDao;

    @Override
    public String touchSynchronization(String jsonData) throws Exception {
        JSONObject jsonObject = synchronizeDepartments(jsonData);
        if (null != jsonObject && jsonObject.getString("errcode").equals("0")) {
            jsonObject = synchronizeUsers(jsonData);
            if (null != jsonObject && jsonObject.getString("errcode").equals("0")) {
                return BaseUtils.succsessObjRespond("同步通讯录成功");
            } else if (null != jsonObject) {
                return BaseUtils.errorrRespond("上传部门信息失败");
            } else {
                return BaseUtils.errorrRespond("同步部门失败");
            }
        } else if (null != jsonObject) {
            return BaseUtils.errorrRespond("上传部门信息失败");
        } else {
            return BaseUtils.errorrRespond("同步部门失败");
        }
    }

    //发送同步部门请求
    @Override
    public JSONObject batchReplaceparty(JSONObject jsonObject) {
        String accessToken = companyTokenFacade.getContactsToken(jsonObject.getString("companyId"));
        jsonObject.remove("companyId");
        String url = WeChatConst.batch_replaceparty_url.replace("ACCESS_TOKEN", accessToken);
        // 调用接口
        return HttpUtil.request(url, "POST", jsonObject.toJSONString());
    }

    //发送同步成员请求
    @Override
    public JSONObject batchReplaceuser(JSONObject jsonObject) {
        String accessToken = companyTokenFacade.getContactsToken(jsonObject.getString("companyId"));
        jsonObject.remove("companyId");
        String url = WeChatConst.batch_replaceuser_url.replace("ACCESS_TOKEN", accessToken);
        // 调用接口
        return HttpUtil.request(url, "POST", jsonObject.toJSONString());
    }

    //同步部门
    public JSONObject synchronizeDepartments(String jsonData) throws Exception {
        //更新wechatId
        companyMessageDao.updateAllDeparts("AND COMPANY_ID = '" + jsonData + "'");
        //获取全部部门信息
        List<JSONObject> jsonObjects = companyMessageDao.getAllDeparts("AND T_SYS_DEPART.COMPANY_ID=?", new Object[]{jsonData});
        List<String> departments = new ArrayList<String>();
        departments.add("部门名称,部门ID,父部门ID,排序");
        //拼装文字信息
        for (JSONObject s : jsonObjects) {
            JSONObject contactsJsonParams = FastJsonConvert.convertJSONToObject(s, JSONObject.class);
            StringBuffer sb = new StringBuffer();
            sb.append(contactsJsonParams.getString("NAME") + ",");
            sb.append(contactsJsonParams.getString("WECHAT_ID") + ",");
            String parentId = contactsJsonParams.getString("PARENT_ID");
            //根部门规则不同,微信(根:1)己(根0)
            if (parentId.equals("0")) {
                sb.append("1" + ",");
            } else {
                sb.append(companyMessageDao.getWechatIdByParentId(parentId) + ",");
            }
            departments.add(sb.toString());
        }
        //获取通讯录token
        String accessToken = companyTokenFacade.getContactsToken(jsonData);
        //同步部门URL
        String requestUrl = WeChatConst.meida_upload_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", "file");
        //创建临时文件
        File f = ContactsSynchronizeFile.send(departments, "batch_party_sample");
        //POST请求发送临时文件
        String filedata = ContactsPOST.send(requestUrl, f);
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(filedata, JSONObject.class);
        if (jsonObject.getString("errcode").equals("0")) {
            String mediaId = jsonObject.getString("media_id");
            jsonObject.clear();
            jsonObject.put("companyId",jsonData);
            jsonObject.put("media_id", mediaId);
            jsonObject = batchReplaceparty(jsonObject);
            if (jsonObject.getString("errcode").equals("0")) {
                return jsonObject;
            } else {
                return null;
            }
        } else {
            return jsonObject;
        }
    }

    public JSONObject synchronizeUsers(String jsonData) throws Exception {
        List<JSONObject> jsonObjects = companyMessageDao.getAllUsers("AND v_sys_user.companyId=?", new Object[]{jsonData});
        List<String> users = new ArrayList<String>();
        users.add("姓名,账号,手机号,所在部门,职位,性别,上级");
        for (JSONObject json : jsonObjects) {
            StringBuffer sb = new StringBuffer();
            //性别规则不同,己(男0女1)微信(男1女2)
            String sex = "1";
            if (json.getString("sex").equals("1")) {
                sex = "2";
            }
            sb.append(json.getString("name") + ",");
            sb.append(json.getString("id") + ",");
            sb.append(json.getString("tel") + ",");
            sb.append(json.getString("wechatDepartId") + ",");
            sb.append(json.getString("roleName") + ",");
            sb.append(sex + ",");
            sb.append(json.getString("parentName"));
            users.add(sb.toString());
        }
        //获取通讯录token
        String accessToken = companyTokenFacade.getContactsToken(jsonData);
        //同步成员URL
        String requestUrl = WeChatConst.meida_upload_url.replace("ACCESS_TOKEN", accessToken).replace("TYPE", "file");
        //创建临时文件
        File f = ContactsSynchronizeFile.send(users, "batch_user_sample");
        //POST请求发送临时文件
        String filedata = ContactsPOST.send(requestUrl, f);
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(filedata, JSONObject.class);
        if (jsonObject.getString("errcode").equals("0")) {
            String mediaId = jsonObject.getString("media_id");
            jsonObject.clear();
            jsonObject.put("companyId",jsonData);
            jsonObject.put("media_id", mediaId);
            //false默认不发送邀请信息(测试时用)---正式时改为true,发送邀请信息
            jsonObject.put("to_invite", false);
            jsonObject = batchReplaceuser(jsonObject);
            if (jsonObject.getString("errcode").equals("0")) {
                return jsonObject;
            } else {
                return null;
            }
        } else {
            return jsonObject;
        }
    }
}
